package com.kaibes.module.token.core;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaibes.module.token.pojo.Token;
import com.kaibes.web.encryption.EncryptionUtils;

@Component
public class TokenEncryptions {

    @Autowired
    private EncryptionUtils encryptionUtils;
    @Autowired
    private ObjectMapper objectMapper;

    public Token readToken(String tokenStr) throws InvalidKeyException, NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
            JsonMappingException, JsonProcessingException {
        return objectMapper.readValue(encryptionUtils.decrypt2String(tokenStr), Token.class);
    }

    public String writeToken(Token token) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
            IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException,
            InvalidAlgorithmParameterException, JsonProcessingException {
        return encryptionUtils.encrypt2String(objectMapper.writeValueAsString(token));
    }

}
